package com.lhkk.inventoryvehicle.led

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Message
import android.util.Log
import android_serialport_api.ComPort
import android_serialport_api.InitDeviceCallback
import androidx.lifecycle.MutableLiveData
import java.util.Locale

object LedManager {

    const val TAG = "DeviceManager"
    const val COM_NAME = "/dev/ttyS7"
    val deviceData = MutableLiveData<String>()
    private var registerAdd = ""
    private val dataHandler = ComPort.DataHandler { comName, buffer, size ->
        val msg = Message.obtain()
        msg.what = 100
        msg.obj = buffer
        msg.arg1 = size
        mHandler.sendMessage(msg)
    }

    private var mHandler = @SuppressLint("HandlerLeak") object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 100) {
                val data = msg.obj as ByteArray
                val len = msg.arg1
                val comdata: String = bytes2HexString(data, len)
                Log.d(TAG, "收到数据：$comdata")
                deviceData.postValue("$registerAdd$comdata")
            }
        }
    }

    fun bytes2HexString(b: ByteArray, len: Int): String {
        var ret = ""
        for (i in 0 until len) {
            var hex = Integer.toHexString(b[i].toInt() and 0xFF)
            if (hex.length == 1) {
                hex = "0$hex"
            }
            ret += hex.uppercase(Locale.getDefault())
        }
        return ret
    }

    /**
     * 连接锁控板串口
     */
    fun deviceInit(comName: String = COM_NAME,
        boardRate: Int = 19200,
        initDeviceCallback: InitDeviceCallback) {
        val isSuccess = ComPort.getInstance().open(comName, boardRate, dataHandler)
        if (isSuccess) {
            initDeviceCallback.initSuccess()
            Log.d(TAG, "打开串口成功")
        } else {
            initDeviceCallback.initFailed()
            Log.d(TAG, "打开串口失败")
        }
    }
}